<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>向量库 Collection 管理</title>
  <!-- 1. jQuery -->
  <script src="{{ url_for('static', filename='js/jquery-3.5.1.min.js') }}"></script>
  <!-- 2. Popper.js -->
  <script src="{{ url_for('static', filename='js/popper.min.js') }}"></script>
  <!-- 3. Bootstrap CSS -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
  <!-- 4. Bootstrap JS -->
  <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
  <!-- 5. Font Awesome -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}">
  <style>
    .actions-column {
      width: 150px;
    }
    .action-btn {
      margin: 0 2px;
    }
  </style>
</head>
<body>
<div class="container">
  <h1 class="mt-4">向量库 Collections</h1>
  
  <!-- 添加搜索和新增按钮区域 -->
  <div class="row mb-3">
    <div class="col-md-6">
      <div class="input-group">
        <input type="text" class="form-control" id="search-input" placeholder="搜索 Collection...">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" id="search-btn">
            <i class="fas fa-search"></i> 搜索
          </button>
        </div>
      </div>
    </div>
    <div class="col-md-6 text-right">
      <button class="btn btn-danger me-2" id="batch-delete-btn" style="display:none; margin-right: 10px;">
        <i class="fas fa-trash"></i> 批量删除
      </button>
      <button class="btn btn-primary" id="new-collection-btn">
        <i class="fas fa-plus"></i> 新建 Collection
      </button>
    </div>
  </div>

  <!-- 表格区域 -->
  <div id="collection-list" class="mt-4">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>
            <input type="checkbox" id="select-all">
          </th>
          <th>Collection 名称</th>
          <th>向量维度</th>
          <th>文档数量</th>
          <th class="actions-column">操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- Collection 列表将通过 AJAX 加载 -->
      </tbody>
    </table>
  </div>

  <!-- 分页控件 -->
  <nav aria-label="Page navigation" class="mt-3">
    <ul class="pagination justify-content-center" id="pagination">
    </ul>
  </nav>

  <!-- 创建/编辑 Collection 的模态框 -->
  <div class="modal fade" id="collectionModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="collectionModalLabel">新建 Collection</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form id="collection-form">
            <div class="form-group">
              <label for="collection-name">Collection 名称</label>
              <input type="text" class="form-control" id="collection-name" required>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="save-collection">保存</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
let currentPage = 1;
const pageSize = 10;
let currentSearch = '';

function loadCollections(page = 1, search = '') {
  currentPage = page;
  currentSearch = search;
  
  $.getJSON("/api/collections", { page, page_size: pageSize, search }, function(data) {
    console.log("Success - Received data:", data);
    renderTable(data.collections);
    renderPagination(data.total);
  });
}

function renderTable(collections) {
  let html = '';
  collections.forEach(function(col) {
    html += '<tr>';
    html += `<td><input type="checkbox" class="collection-checkbox" data-name="${col.name}"></td>`;
    html += `<td><a href="/collection/${encodeURIComponent(col.name)}">${col.name}</a></td>`;
    html += `<td>${col.dimension || '-'}</td>`;
    html += `<td>${col.count || 0}</td>`;
    html += '<td class="actions-column">';
    html += `<button class="btn btn-sm btn-info action-btn edit-collection" data-name="${col.name}" title="编辑">
              <i class="fas fa-edit"></i>
            </button>`;
    html += `<button class="btn btn-sm btn-danger action-btn delete-collection" data-name="${col.name}" title="删除">
              <i class="fas fa-trash"></i>
            </button>`;
    html += '</td>';
    html += '</tr>';
  });
  $("#collection-list tbody").html(html);
}

function renderPagination(total) {
  const totalPages = Math.ceil(total / pageSize);
  let html = '';
  
  if (totalPages <= 1) {
    $('#pagination').html('');
    return;
  }

  html += `
    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
      <a class="page-link" href="#" data-page="${currentPage-1}">&laquo;</a>
    </li>`;

  for (let i = 1; i <= totalPages; i++) {
    html += `
      <li class="page-item ${i === currentPage ? 'active' : ''}">
        <a class="page-link" href="#" data-page="${i}">${i}</a>
      </li>`;
  }

  html += `
    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
      <a class="page-link" href="#" data-page="${currentPage+1}">&raquo;</a>
    </li>`;

  $('#pagination').html(html);
}

$(document).ready(function() {
  loadCollections();

  // 搜索功能
  $('#search-btn').click(function() {
    const searchText = $('#search-input').val();
    loadCollections(1, searchText);
  });

  // 回车搜索
  $('#search-input').keypress(function(e) {
    if(e.which == 13) {
      $('#search-btn').click();
    }
  });

  // 分页点击
  $('#pagination').on('click', '.page-link', function(e) {
    e.preventDefault();
    const page = $(this).data('page');
    if (page && !$(this).parent().hasClass('disabled')) {
      loadCollections(page, currentSearch);
    }
  });

  // 新建按钮点击
  $('#new-collection-btn').click(function() {
    $('#collectionModalLabel').text('新建 Collection');
    $('#collection-name').val('');
    $('#collectionModal').modal('show');
  });

  // 保存 Collection
  $('#save-collection').click(function() {
    const name = $('#collection-name').val();
    if (!name) {
      alert('请输入 Collection 名称');
      return;
    }

    $.ajax({
      url: '/api/collections',
      method: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({name: name}),
      success: function(res) {
        $('#collectionModal').modal('hide');
        loadCollections(currentPage, currentSearch);
      },
      error: function(err) {
        alert('错误：' + err.responseJSON?.error || '未知错误');
      }
    });
  });

  // 删除 Collection
  $("#collection-list").on("click", ".delete-collection", function() {
    var name = $(this).data("name");
    if (confirm("确定删除 Collection：" + name + " ?")) {
      $.ajax({
        url: '/api/collections/' + encodeURIComponent(name),
        method: 'DELETE',
        success: function(res) {
          alert("Collection 删除成功！");
          loadCollections();
        },
        error: function(err) {
          alert("错误：" + err.responseJSON.error);
        }
      });
    }
  });

  // 编辑 Collection
  $("#collection-list").on("click", ".edit-collection", function() {
    var name = $(this).data("name");
    // TODO: 实现编辑功能，可以添加一个模态框来编辑 collection 的属性
    alert("编辑功能待实现");
  });

  // 全选/取消全选
  $('#select-all').change(function() {
    const isChecked = $(this).prop('checked');
    $('.collection-checkbox').prop('checked', isChecked);
    updateBatchDeleteButton();
  });

  // 单个复选框变化时更新批量删除按钮状态
  $('#collection-list').on('change', '.collection-checkbox', function() {
    updateBatchDeleteButton();
  });

  // 更新批量删除按钮显示状态
  function updateBatchDeleteButton() {
    const checkedCount = $('.collection-checkbox:checked').length;
    $('#batch-delete-btn').toggle(checkedCount > 0);
    // 更新全选框状态
    const totalCount = $('.collection-checkbox').length;
    $('#select-all').prop('checked', checkedCount > 0 && checkedCount === totalCount);
  }

  // 批量删除按钮点击事件
  $('#batch-delete-btn').click(function() {
    const selectedCollections = $('.collection-checkbox:checked').map(function() {
      return $(this).data('name');
    }).get();

    if (selectedCollections.length === 0) {
      return;
    }

    if (confirm(`确定要删除选中的 ${selectedCollections.length} 个 Collection 吗？`)) {
      const deletePromises = selectedCollections.map(name => {
        return $.ajax({
          url: '/api/collections/' + encodeURIComponent(name),
          method: 'DELETE'
        });
      });

      Promise.all(deletePromises)
        .then(() => {
          alert('批量删除成功！');
          loadCollections(currentPage, currentSearch);
        })
        .catch(err => {
          alert('删除过程中发生错误：' + err.responseJSON?.error || '未知错误');
          loadCollections(currentPage, currentSearch);
        });
    }
  });
});
</script>
</body>
</html>